<template>
    <div class="ui container">
        <div class="ui large header">个人中心</div>
        <div class="ui grid">
            <div class="five wide stackable column">
                <div class="ui vertical menu">
                    <div class="item header">
                        <div class="img-con"  @click="showModal">
                            <img :src="avatar" id="lalala" alt="avatar.png">
                            <div class="img-con__cover">
                                切换头像
                            </div>
                        </div>
                        <div class="text-con">
                        <span class="ui large header" >{{nickName}}</span>
                        <p >{{memo}}</p>
                        </div>
                        <!-- <i class="ui blue edit icon" @click="editing = false; isInfoEditable=true" v-if="editing"></i><a href="javascript:void(0)" v-else @click="editing = true; isInfoEditable=false" class="save">保存</a> -->
                    </div>
                    <div class="item" :class="activeMenu[index] ? 'active': ''" v-for="(item, index) in accountMenu" :key="index">
                        <a href="javescript: void(0)" @click="$router.push({path: item.url});activeMenu.fill(false);activeMenu = Object.assign([], activeMenu);$set(activeMenu, index, true)">{{item.label}}</a>
                        <i class="ui label" v-if="item.num">{{item.num}}</i>
                    </div>
                </div>
            </div>
            <div class="ten wide stackable column">
                <router-view></router-view>
            </div>
            <!-- upload image popup start-->
            <div class="ui modal">
                <div class="content">
                    <div class="ui secondary pointing menu">
                        <a href="javescript: void(0)" 
                            @click="pointingActiveIndex = (index + 1)" 
                            class="item" 
                            :class="{'active': pointingActiveIndex === (index + 1)}" 
                            v-for="(item, index) in pointingMenu" 
                            :key="index">{{item}}图片</a>
                        <!-- <a href="javescript: void(0)" @click="pointingActiveIndex = 2" class="item">裁剪图片</a> -->
                    </div>
                    <div class="image-uploader__area" v-show="pointingActiveIndex === 1">
                        <div class="ui center aligned container">
                            <i class="cloud upload icon"></i>将图片拖至此处 或 <label for="imageUploader" style="color: #4183c4; cursor: pointer">选择文件</label>
                            <form enctype="multipart/form-data">
                                <input type="file" accept="image/*" id="imageUploader" style="position: absolute;clip: rect(0,0,0,0)" @change="uploadImg">
                            </form>
                        </div>
                    </div>
                    <div class="image-cut__area" v-show="pointingActiveIndex === 2">
                        <div class="image-cut__con">
                            <img :src="imgPreviewUrl" id="imgPreview" alt="">
                        </div>
                    </div>
                </div>
                <div class="actions clearfix">
                    <div class="ui right floated ok blue button" @click="uploadAvatar">确定上传</div>
                    <div class="ui right floated cancel button">取消</div>
                </div>
            </div>
            <!-- upload image popup end-->
        </div>
    </div>
</template>
<script>
import {api_account, serverAssetsRoot} from '@/api'
import {mapState, mapMutations} from 'vuex'
import imgCliper from '@/utils/imgCliper'
export default {
    name: 'userinfo',
    data () {
        return {
            accountMenu: [
                {
                    label: '账号管理',
                    num: '',
                    url: '/userinfo/account/basic'
                },
                {
                    label: '我参加的',
                    num: 5,
                    url: '/'
                },
                {
                    label: '好友',
                    num: 95,
                    url: '/userinfo/friends/all'
                }
            ],
            activeMenu: [true, false, false],
            avatar: '',
            nickName: '',
            memo: '',
            pointingMenu: ['上传', '裁剪'],
            pointingActiveIndex: 1,
            imgPreviewUrl: '',
            newAvatarParams: {},
            result: '',
            api: ''
        }
    },
    mounted () {
        this.targetDraggable('.image-uploader__area', this.imgPreviewUrl)
        this.updateUserInfo()
        this.api = api_account
    },
    methods: {
        ...mapMutations(['SET_USERINFO']),
        getUserInfo () {
            this.$http({
                method: 'get',
                url: api_account + '/basic'
            }).then()
        },
        showModal () {
            $('.ui.modal').modal('show')
        },
        uploadImg () {
            let file = $('#imageUploader')[0].files[0],
                reader = new FileReader()
            reader.onloadend = () => {
                this.imgPreviewUrl = reader.result
                this.pointingActiveIndex = 2
            }

            if (file) {
                reader.readAsDataURL(file)
            } else {
                this.imgPreviewUrl = ''
            }
        },
        // 对象可以接受图片的拖拽
        targetDraggable (selector, previewUrl) {
            $(selector).on({
                'dragenter': (e) => {
                    e.preventDefault()
                },
                'dragover': (e) => {
                    e.preventDefault()
                },
                'drop': (e) => {
                    e.stopPropagation()
                    e.preventDefault()
                    // let file = e.dataTransfer.files[0]

                    let file = e.originalEvent.dataTransfer.files[0]
                    $('#imgPreview').on('load', () => {
                        this.newAvatarParams = imgCliper($('#imgPreview')[0])
                    })
                    this.imgPreviewUrl = window.URL.createObjectURL(file)
                    this.pointingActiveIndex = 2
                }
            })
        },
        // 上传头像
        uploadAvatar () {
            let { x, y, w, h } = this.newAvatarParams
            console.log(-x.val(), -y.val(), w.val(), h.val(), 'xywh', $('#imgPreview')[0])
            let canvas = $('<canvas width="' + w.val() + '" height="' + h.val() + '"></canvas>')[0],
                ctx = canvas.getContext('2d')
            ctx.drawImage($('#imgPreview')[0], x.val(), y.val(), w.val(), h.val(), 0, 0, w.val(), h.val())
            // base64转blob
            let data = canvas.toDataURL().split(',')[1]
            data = window.atob(data)
            let unit8data = new Uint8Array(data.length)
            for (let i = 0; i < data.length; i++) {
                unit8data[i] = data.charCodeAt(i)
            };

            let blob = new Blob([unit8data], {type: 'image/png'})
            // 添加至FormData用于提交
            let formData = new FormData()
            formData.append('avatar', blob)
            // formdata无法被console.log打印
            // console.log(formData, 'formData')

            // 这种方式提交会导致formdata为空
            // this.$http({
            //     method: 'post',
            //     url: api_account + '/avatar',
            //     headers: {'Content-Type': 'multipart/form-data'},
            //     data: {
            //         formData: formData
            //     }
            // })
            this.$http.post(api_account + '/avatar', formData)
            .then(_ => {
                this.avatar = canvas.toDataURL('image/png')
                this.$message({
                    message: '修改成功',
                    type: 'success'
                })
            })
        },
        updateUserInfo () {
            this.$http.get(api_account + '/basic').then(res => {
                let { nickname, memo, avatar } = res.data.data
                this.result = res.data
                this.SET_USERINFO(res.data.data)
                this.$nextTick(() => {
                    [this.nickName, this.memo, this.avatar] = [nickname, memo, serverAssetsRoot + avatar]
                })
            })
        }
    }
}
</script>
<style lang="stylus" scoped>
$header_icon_size = 60px

.ui.vertical.menu
    width 300px

.item.header
    .img-con
        width $header_icon_size
        height $header_icon_size
        border-radius ($header_icon_size / 2)
        overflow hidden
        display inline-block
        vertical-align middle
        position relative
        cursor pointer
        img
            width 100%
            height 100%

.img-con:hover .img-con__cover
    position absolute
    bottom 0
    top 0
    line-height $header_icon_size
    font-size 10px
    background #0000007a
    color white
    width 100%
    text-align center

.ui.edit.icon
    cursor pointer
.text-con
    margin-left 10px
    display inline-block
    vertical-align middle
.save
    position absolute
    right 20px

.image-uploader__area
    border: 1px dashed grey
    padding 50px 20px

.image-cut__con
    max-width 800px
    border 1px dashed grey
    #imgPreview
        width 100%
        // 这里要设置height 是auto ， 否则imgCliper会导致图片高度为0
        height auto
</style>
